package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.GoodsBoxDetail;
import com.lvy.hczn.front.system.domain.business.SaleOrderDetail;
import com.lvy.hczn.front.system.domain.business.Spu;
import com.lvy.hczn.front.system.domain.business.Warehouse;
import com.lvy.hczn.front.system.service.SpuService;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.transmit.domain.ProductSupplierGoods;
import com.lvy.hczn.transmit.domain.dto.cteck.CreditNote;
import com.lvy.hczn.transmit.service.ProductSupplierGoodsService;
import com.lvy.hczn.transmit.service.TCreditNoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TCreditNoteServiceImpl implements TCreditNoteService {

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private ProductSupplierGoodsService productSupplierGoodsService;

    @Override
    public void syncCreditNoteData(ParamInfo paramInfo) {
        if (paramInfo.getData() == null) {
            throw new UtilException("数据为空");
        }
        CreditNote creditNote = JSON.parseObject(JSON.toJSONString(paramInfo.getData()), CreditNote.class);
        if (StrUtil.hasEmpty(creditNote.getCreditNote(), creditNote.getServiceCode())) {
            throw new UtilException("退货单或销售单为空");
        }
        if (StrUtil.isEmpty(creditNote.getWarehouseCode())) {
            throw new UtilException("仓库编号为空");
        }
        Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, creditNote.getWarehouseCode()));
        if (warehouse == null) {
            throw new UtilException("仓库信息不存在，请检查仓库编号：" + creditNote.getWarehouseCode());
        }
        log.error("syncCreditNoteDataParam:{}", JSON.toJSONString(paramInfo));
        creditNote.setSourceId(Constants.SOURCE_ID_DEFAULT + creditNote.getCreditNote());
        creditNote.setType("2");
        creditNote.setStatus("3");
        creditNote.setSaleOrderCode(creditNote.getCreditNote());
        creditNote.setDeliveryCode(creditNote.getCreditNote());
        creditNote.setReturnOfGoods(true);
        if (creditNote.getList() == null || creditNote.getList().isEmpty()) {
            throw new UtilException("退货单商品明细为空");
        }
        creditNote.setMemberCode(creditNote.getBuyerId());
        if (StrUtil.isEmpty(creditNote.getBuyerName())) {
            creditNote.setName(creditNote.getBuyerId());
        } else {
            creditNote.setName(creditNote.getBuyerName());
        }

        //根据是否预售分组
        LinkedHashMap<Integer, List<SaleOrderDetail>> boxCodeMap = creditNote.getList().stream().collect(Collectors.groupingBy(SaleOrderDetail::getOutStock, LinkedHashMap::new, Collectors.toList()));
        boxCodeMap.forEach((k, v) -> {
            CreditNote creditNoteInfo;
            creditNoteInfo = creditNote;
            creditNoteInfo.setOutStock(k);
            creditNoteInfo.setList(new ArrayList<>());
            v.forEach(saleOrderDetail -> {
                ProductSupplierGoods productSupplierGoods = productSupplierGoodsService.getOne(Wrappers.<ProductSupplierGoods>lambdaQuery().eq(ProductSupplierGoods::getProductSysCode, saleOrderDetail.getSpuCode()));
                if (productSupplierGoods == null) {
                    throw new UtilException("商品不存在，请检查商品编号:" + saleOrderDetail.getSpuCode());
                }
                if (StrUtil.isEmpty(saleOrderDetail.getDataType())) {
                    saleOrderDetail.setDataType(Constants.WAREHOUSING_ENTRY_DATA_TYPE_SEVEN);
                }
                saleOrderDetail.setSpuId(productSupplierGoods.getId());
                if (StrUtil.isEmpty(saleOrderDetail.getSaleOrderCode())) {
                    saleOrderDetail.setSaleOrderCode(creditNote.getSaleOrderCode());
                }
                saleOrderDetail.setBatchCode(saleOrderDetail.getSaleOrderCode());
                if (StrUtil.isEmpty(saleOrderDetail.getSpecCode())) {
                    saleOrderDetail.setSpecCode(saleOrderDetail.getSkuCode());
                }
                saleOrderDetail.setSourceId(saleOrderDetail.getId() + Constants.SOURCE_ID_DEFAULT + creditNote.getCreditNote());
                saleOrderDetail.setStatus("3");
                saleOrderDetail.setId(null);
                saleOrderDetail.setWeight(new BigDecimal(saleOrderDetail.getQuantity()).multiply(saleOrderDetail.getWeight()).setScale(2, RoundingMode.HALF_UP));
                creditNoteInfo.getList().add(saleOrderDetail);
            });
            String topic = warehouseService.selectRegionAreaTopic(warehouse);
            String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_CREDIT_NOTE_TAG;
            ParamInfo info = new ParamInfo();
            info.setData(creditNoteInfo);
            try {
                producerUtil.sendAsyncMsg(topic, tag, JSON.toJSONString(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
            } catch (Exception e) {
                log.error("syncCreditNoteDataError:", e);
                throw new UtilException("信息发送异常");
            }
        });
    }
}
